<template>
  <a-drawer v-model:visible="visible" height="90%" placement="bottom">
    <div class="flex gap-2 h-full">
      <div class="w-2/12 overflow-auto">
        <a-typography-title :heading="6">数据表</a-typography-title>
        <a-input-search v-model="tableKeyword" />
        <div v-for="item in tableList" :title="item.table_comment">
          <a-typography-paragraph copyable ellipsis :type="cur_table.table_name === item.table_name ? 'primary' : ''">
            {{ item.table_name }}
            <icon-exclamation-circle class="cursor-pointer" title="查看字段" @click="handleClick(item)" />
          </a-typography-paragraph>
        </div>
      </div>
      <div class="w-2/12 overflow-auto">
        <a-typography-title :heading="6"> 字段列表</a-typography-title>
        <div class="truncate" v-for="item in fields" :title="item.name + item.comment">
          <a-typography-paragraph copyable ellipsis>
            {{ item.name }}
            {{ item.comment }}
          </a-typography-paragraph>
        </div>
      </div>
      <div class="w-8/12 overflow-auto">
        <a-form auto-label-width :model="formModel">
          <div class="flex">
            <a-form-item label="视图名称" field="table_name">
              <a-input v-model="formModel.table_name" placeholder="请输入中文名称" />
            </a-form-item>
            <a-form-item label="视图名" help="只能是字母" field="view_name">
              <a-input v-model="formModel.view_name" />
            </a-form-item>
          </div>
          <div class="flex gap-4">
            <div class="w-7/12">
              <a-form-item label="视图定义" field="view_sql">
                <ma-code-editor v-model="formModel.view_sql" height="300" language="mysql" />
              </a-form-item>
            </div>
            <div class="w-5/12">
              <a-form-item label="变量设置" field="variable">
                <ma-code-editor v-model="formModel.variable" height="300" />
              </a-form-item>
            </div>
          </div>
        </a-form>
        <a-table
          v-if="isView"
          :columns="columns"
          :data="data"
          :loading="loading"
          sticky-header
          :scroll="{
            x: 2000,
            y: 200
          }"
          :scrollbar="{
            x: '120%',
            y: '100%'
          }"
        />
      </div>
    </div>
    <template #footer>
      <a-space>
        <a-button type="primary" @click="prview">预览</a-button>
        <a-button type="primary" @click="save">保存</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>
<script setup>
import dayjs from "dayjs"
import source from "@/views/datasource/api/source"
import { inject, ref } from "vue"
import { Message } from "@arco-design/web-vue"
import tool from "@/utils/tool.js"

const BiCube = inject("BiCube", {})
const { dataset } = BiCube.pageStatus
const { tableList } = BiCube.schemaStatus
const visible = defineModel("visible", false)
const model = defineModel()

const formModel = ref({
  ...{
    table_name: "",
    view_name: "bi_view_" + dayjs().format("YYYYMMDDHHmmss"),
    view_sql: "",
    datasource_id: "",
    is_edit: false,
    variable: ""
  },
  ...model.value
})
// select * from la_admin
const isView = ref("false")
const columns = ref([])
const loading = ref(false)
const data = ref([])
const prview = () => {
  loading.value = true
  model.value.datasource_id = dataset.datasource_id
  source.viewsql(model.value).then((res) => {
    data.value = res.data
    if (res.data.length === 0) {
      Message.error("无数据")
      return
    }
    isView.value = true
    loading.value = false
    columns.value = Object.keys(res.data[0]).map((key) => {
      return {
        title: key,
        dataIndex: key,
        ellipsis: true,
        tooltip: true,
        minWidth: 100
      }
    })
  })
}

const save = () => {
  formModel.value.datasource_id = dataset.datasource_id
  source.createView(formModel.value).then((res) => {
    visible.value = false
    Message.success("保存成功")
    BiCube.schemaStatus.initData()
  })
}

const fields = ref([])
const cur_table = ref({})
const handleClick = (item) => {
  fields.value = []
  Message.loading("加载中...")
  cur_table.value = item
  source
    .getFieldsList({
      datasource_id: dataset.datasource_id,
      table_name: item.table_name
    })
    .then((res) => {
      fields.value = res.data
    })
}

const tableKeyword = ref("")
watch(
  () => tableKeyword.value,
  (val) => {
    tableList.value = tool.searchEvent(val, tableList.value, ["table_name"], "tableKeyword")
  }
)

const fieldKeyword = ref("")
watch(
  () => fieldKeyword.value,
  (val) => {
    fields.value = tool.searchEvent(val, fields.value, ["name"], "fieldKeyword", true)
  }
)
</script>
<style scoped></style>
